package com.imut.lagain.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imut.lagain.entity.HealthReminder;
import com.imut.lagain.service.IHealthReminderService;
import com.imut.lagain.util.JwtUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.*;
import jakarta.validation.Valid;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 健康提醒控制器
 */
@RestController
@RequestMapping("/api/health-reminders")
@RequiredArgsConstructor
@Validated
public class HealthReminderController {
    private static final Logger log = LoggerFactory.getLogger(HealthReminderController.class);


    private final IHealthReminderService healthReminderService;
    private final JwtUtil jwtUtil;
    
    /**
     * 创建健康提醒
     * @param authorization JWT令牌
     * @param request 创建请求
     * @return 创建结果
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createHealthReminder(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @Valid @RequestBody CreateHealthReminderRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            HealthReminder healthReminder = new HealthReminder();
            healthReminder.setUserId(userId);
            healthReminder.setReminderType(request.getReminderType());
            healthReminder.setRemindTime(request.getRemindTime());
            healthReminder.setMessage(request.getMessage());
            healthReminder.setIsCompleted(request.getIsCompleted());
            
            boolean saved = healthReminderService.save(healthReminder);
            
            if (saved) {
                response.put("success", true);
                response.put("data", healthReminder);
                response.put("message", "健康提醒创建成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "健康提醒创建失败");
                return ResponseEntity.internalServerError().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to create health reminder", e);
            response.put("success", false);
            response.put("message", "创建健康提醒失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取健康提醒详情
     * @param authorization JWT令牌
     * @param id 提醒ID
     * @return 提醒详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getHealthReminder(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @PathVariable @Min(1) Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            HealthReminder healthReminder = healthReminderService.getById(id);
            
            if (healthReminder == null) {
                response.put("success", false);
                response.put("message", "健康提醒不存在");
                return ResponseEntity.ok(response);
            }
            if (!healthReminder.getUserId().equals(userId)) {
                response.put("success", false);
                response.put("message", "无权访问该提醒");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }
            
            response.put("success", true);
            response.put("data", healthReminder);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get health reminder", e);
            response.put("success", false);
            response.put("message", "获取健康提醒失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 更新健康提醒
     * @param authorization JWT令牌
     * @param id 提醒ID
     * @param request 更新请求
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateHealthReminder(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @PathVariable @Min(1) Long id,
            @Valid @RequestBody UpdateHealthReminderRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            HealthReminder healthReminder = healthReminderService.getById(id);
            
            if (healthReminder == null) {
                response.put("success", false);
                response.put("message", "健康提醒不存在");
                return ResponseEntity.ok(response);
            }
            if (!healthReminder.getUserId().equals(userId)) {
                response.put("success", false);
                response.put("message", "无权访问该提醒");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }
            
            healthReminder.setReminderType(request.getReminderType());
            healthReminder.setRemindTime(request.getRemindTime());
            healthReminder.setMessage(request.getMessage());
            healthReminder.setIsCompleted(request.getIsCompleted());
            
            boolean updated = healthReminderService.updateById(healthReminder);
            
            if (updated) {
                response.put("success", true);
                response.put("data", healthReminder);
                response.put("message", "健康提醒更新成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "健康提醒更新失败");
                return ResponseEntity.internalServerError().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to update health reminder", e);
            response.put("success", false);
            response.put("message", "更新健康提醒失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 删除健康提醒
     * @param authorization JWT令牌
     * @param id 提醒ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteHealthReminder(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @PathVariable @Min(1) Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            HealthReminder healthReminder = healthReminderService.getById(id);
            
            if (healthReminder == null) {
                response.put("success", false);
                response.put("message", "健康提醒不存在");
                return ResponseEntity.ok(response);
            }
            if (!healthReminder.getUserId().equals(userId)) {
                response.put("success", false);
                response.put("message", "无权访问该提醒");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }
            
            boolean removed = healthReminderService.removeById(id);
            
            if (removed) {
                response.put("success", true);
                response.put("message", "健康提醒删除成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "健康提醒删除失败");
                return ResponseEntity.internalServerError().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to delete health reminder", e);
            response.put("success", false);
            response.put("message", "删除健康提醒失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 分页查询健康提醒
     * @param authorization JWT令牌
     * @param page 页码
     * @param size 每页大小
     * @param reminderType 提醒类型
     * @return 提醒列表
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getHealthReminders(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @RequestParam(defaultValue = "1") @Min(1) int page,
            @RequestParam(defaultValue = "10") @Min(1) @Max(100) int size,
            @RequestParam(required = false) String reminderType) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            Page<HealthReminder> pageParam = new Page<>(page, size);
            IPage<HealthReminder> healthReminderPage;
            
            if (reminderType != null && !reminderType.isEmpty()) {
                healthReminderPage = healthReminderService.findByUserIdAndType(userId, reminderType, pageParam);
            } else {
                healthReminderPage = healthReminderService.page(pageParam, 
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<HealthReminder>()
                        .eq(HealthReminder::getUserId, userId)
                        .orderByDesc(HealthReminder::getRemindTime));
            }
            
            response.put("success", true);
            response.put("data", healthReminderPage);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get health reminders", e);
            response.put("success", false);
            response.put("message", "获取健康提醒列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 根据时间范围查询健康提醒
     * @param authorization JWT令牌
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 提醒列表
     */
    @GetMapping("/time-range")
    public ResponseEntity<Map<String, Object>> getHealthRemindersByTimeRange(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            List<HealthReminder> healthReminders = healthReminderService.findByUserIdAndTimeRange(userId, startTime, endTime);
            
            response.put("success", true);
            response.put("data", healthReminders);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get health reminders by time range", e);
            response.put("success", false);
            response.put("message", "获取健康提醒失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 查询待处理的健康提醒
     * @param authorization JWT令牌
     * @return 提醒列表
     */
    @GetMapping("/pending")
    public ResponseEntity<Map<String, Object>> getPendingHealthReminders(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            LocalDateTime currentTime = LocalDateTime.now();
            
            List<HealthReminder> healthReminders = healthReminderService.findPendingReminders(userId, currentTime);
            
            response.put("success", true);
            response.put("data", healthReminders);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get pending health reminders", e);
            response.put("success", false);
            response.put("message", "获取待处理健康提醒失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 标记提醒为已完成
     * @param authorization JWT令牌
     * @param id 提醒ID
     * @return 更新结果
     */
    @PutMapping("/{id}/complete")
    public ResponseEntity<Map<String, Object>> markAsCompleted(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @PathVariable @Min(1) Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            HealthReminder healthReminder = healthReminderService.getById(id);
            
            if (healthReminder == null) {
                response.put("success", false);
                response.put("message", "健康提醒不存在");
                return ResponseEntity.ok(response);
            }
            if (!healthReminder.getUserId().equals(userId)) {
                response.put("success", false);
                response.put("message", "无权访问该提醒");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }
            
            boolean completed = healthReminderService.markAsCompleted(id);
            
            if (completed) {
                response.put("success", true);
                response.put("message", "健康提醒标记为已完成");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "健康提醒标记失败");
                return ResponseEntity.internalServerError().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to mark health reminder as completed", e);
            response.put("success", false);
            response.put("message", "标记健康提醒失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取未完成提醒数量
     * @param authorization JWT令牌
     * @return 提醒数量
     */
    @GetMapping("/pending-count")
    public ResponseEntity<Map<String, Object>> getPendingRemindersCount(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            Long count = healthReminderService.countPendingReminders(userId);
            
            response.put("success", true);
            response.put("data", count);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get pending reminders count", e);
            response.put("success", false);
            response.put("message", "获取未完成提醒数量失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    @Data
    public static class CreateHealthReminderRequest {
        @NotBlank(message = "提醒类型不能为空")
        private String reminderType;
        
        @NotNull(message = "提醒时间不能为空")
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime remindTime;
        
        @NotBlank(message = "提醒消息不能为空")
        @Size(max = 500, message = "提醒消息长度不能超过500个字符")
        private String message;
        
        private Boolean isCompleted = false;
        
        public String getReminderType() { return reminderType; }
        public LocalDateTime getRemindTime() { return remindTime; }
        public String getMessage() { return message; }
        public Boolean getIsCompleted() { return isCompleted; }
    }
    
    @Data
    public static class UpdateHealthReminderRequest {
        @NotBlank(message = "提醒类型不能为空")
        private String reminderType;
        
        @NotNull(message = "提醒时间不能为空")
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime remindTime;
        
        @NotBlank(message = "提醒消息不能为空")
        @Size(max = 500, message = "提醒消息长度不能超过500个字符")
        private String message;
        
        private Boolean isCompleted;
        
        public String getReminderType() { return reminderType; }
        public LocalDateTime getRemindTime() { return remindTime; }
        public String getMessage() { return message; }
        public Boolean getIsCompleted() { return isCompleted; }
    }
}

